//
//  AY_WebViewController.m
//  AiYue
//
//  Created by mac on 2023/12/1.
//

#import "AY_WebViewController.h"
#import <WebKit/WebKit.h>
#import "AY_WebViewProgress.h"

@interface AY_WebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic,strong) AY_WebViewProgress *progressLine;
@property (nonatomic,strong) WKUserContentController *userController;
@end

@implementation AY_WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self updateNavigationItems];
    [self.view addSubview:self.webView];
    [self addProgressLineSet];
    
    NSURL *url = [NSURL URLWithString:self.fullPath];
//    NSString *formattedString = [NSString stringWithFormat:@"%@?token=%@", url, [];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request addValue:[self getToken] forHTTPHeaderField:@"token"];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:formattedString];
    
    [self.webView loadRequest:request];
}

// JS 调用时触发此方法
- (void)userContentController:(WKUserContentController *)userContentController
            didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"getToken"]) {
        // 获取 JS 传递过来的参数
//        NSDictionary *params = message.body;
        
        // 执行 iOS 原生方法并将结果返回给 JS
        NSString *result = [self getToken];
        
        NSString *escapedResult = [result stringByReplacingOccurrencesOfString:@"\n" withString:@"\\\n"];
        NSString *escapedResult2 = [escapedResult stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];


        // 将结果返回给 JS
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"getToken('%@');", escapedResult2] completionHandler:nil];
        
    }
}

- (NSString *)getToken {
    NSDictionary *dic = @{
        @"uuid": [AYTool getUUID],
        @"appCode": SXAPPBUNDLEID,
        @"appVersion": APPVERSION,
        @"gmtCreate": [AYTool getTimeNow],
        @"channelCode": CHANNELCODE,
    };

    NSString *token = [AYTool encrypt:[AYTool convertToJSONData:dic]];
    if (kStringIsEmpty(token)) {
        return @"";
    }
    NSDictionary *dic1 = @{
        @"token": token,
        @"appCode": APPVERSION,
        @"packageName": SXAPPBUNDLEID,
        @"channelCode": CHANNELCODE,
        @"deviceType": @"iOS",
    };
    NSString *xToken = [AYTool convertToJSONData:dic1];

    return xToken;
}

- (void)updateNavigationItems{
    if (self.webView.canGoBack) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    } else {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

//WkWebView的 回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    [self barStyleBlack];
    if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
        self.gk_navigationItem.title = self.webView.title;
         } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
         }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    
    }
}

- (void)addProgressLineSet {
    self.progressLine = [[AY_WebViewProgress alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, 3)];
    self.progressLine.lineColor = THEME_COLOR;
    [self.view addSubview:self.progressLine];
}

#pragma -mark webViewDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [self.progressLine startLoadingAnimation];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self.progressLine endLoadingAnimation];
    [self updateNavigationItems];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    [self.progressLine endLoadingAnimation];
    ShowToast(@"加载失败");
}

-(WKWebView *)webView{
    if (_webView == nil) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        self.userController = [[WKUserContentController alloc] init];
        configuration.userContentController = self.userController;
        [configuration.userContentController addScriptMessageHandler:self name:@"getToken"];
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, SCREEN_H - GK_STATUSBAR_NAVBAR_HEIGHT) configuration:configuration];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
        
        

    }
    return _webView;
}

- (void)dealloc{
    [_webView removeObserver:self forKeyPath:@"title"];
}
@end
